package cn.itrip.dao;

import cn.itrip.common.Constants;
import cn.itrip.common.EmptyUtils;
import cn.itrip.common.Page;
import org.apache.solr.client.solrj.SolrQuery;
import org.apache.solr.client.solrj.impl.HttpSolrClient;
import org.apache.solr.client.solrj.impl.XMLResponseParser;
import org.apache.solr.client.solrj.response.QueryResponse;

import java.util.List;

/**
 * @author jie
 * @date 2019/5/7 -11:12
 */
public class BaseQuery<T> {

    private HttpSolrClient httpSolrClient;

    public BaseQuery(String url){
        httpSolrClient = new HttpSolrClient(url);
        httpSolrClient.setParser(new XMLResponseParser());
        httpSolrClient.setConnectionTimeout(1000);
    }

    public Page<T> queryPage(SolrQuery query,Integer pageNo,Integer pageSize,Class clazz) throws Exception{
        Integer rows = EmptyUtils.isEmpty(pageSize)?Constants.DEFAULT_PAGE_SIZE:pageSize;
        Integer currPage = EmptyUtils.isEmpty(pageNo)?Constants.DEFAULT_PAGE_NO-1:pageNo-1;
        Integer start = rows*currPage;
        query.setRows(rows);
        query.setStart(start);

        QueryResponse queryResponse = httpSolrClient.query(query);
        List list = queryResponse.getBeans(clazz);
        Page page = new Page();
        page.setRows(list);
        return page;
    }
}
